<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>课程管理</strong>
    </h2>
    <div class="top-info">
      <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getCourseList" />
      <el-button type="primary" @click="addCourse">新增课程</el-button>
    </div>
    <RuifoxTable
      v-loading="tableLoading"
      :table-data="courseData"
      :field-list="fieldList"
      :default-index="true"
      :default-checkbox="true"
      :lazy="true"
    >
      <!-- 课程封面图 -->
      <template #coverImg="{ element }" >
        <img :src="element.coverImg" alt="" class="course-thumb" style="width: 120px;height: 70px;">
      </template>
      <!-- 课程类型列 -->
      <template #type="{ element }" >
        <el-tag v-if="element.type == 'PUBLIC'" type="primary">公开</el-tag>
        <el-tag v-if="element.type == 'PRIVILEGED'" type="success">私有</el-tag>
        <!-- <el-tag v-if="element.type == ORGANIZATION" type="success">组织</el-tag> -->
      </template>

      <!-- 课程状态 -->
      <template #status="{ element }" >
        <el-tag v-if="element.status == 'DRAFT'" type="primary">草稿</el-tag>
        <el-tag v-if="element.status == 'UNDER_REVIEW'" type="primary">审核中</el-tag>
        <el-tag v-if="element.status == 'PUBLISHED'" type="success">已发布</el-tag>
        <el-tag v-if="element.status == 'DISUSE'" type="danger">停用</el-tag>
      </template>

      <template #default-checkbox="{ element }">
        <div class="table-div-check">
          <el-checkbox
            class="unmover"
            v-model="element.checked"
            @change="handleCheckTable(element.id)"
            size=""
          />
        </div>
      </template>
      <template #creatTime="{ element }">
        {{ dayjs(element.createTime).format("YYYY-MM-DD") }}
      </template>
      <template #options="{ element }">
        <div class="table-td-option unmover">
          <el-button
            type="primary"
            link
            @click="editCourseInfo(element)"
          >
            编辑信息
          </el-button>
          <el-button
            type="primary"
            link
            @click="editCourseContent(element)"
          >
            课程详情
          </el-button>
          <el-button
            type="primary"
            link
            @click="removeCourse(element)"
          >
            删除
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link unmover">
              <i class="iconfont">&#xe78d;</i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="element.status != 'DRAFT'" @click="changeCourseStatus(element,'DRAFT(draft,草稿)')">草稿</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'UNDER_REVIEW'" @click="changeCourseStatus(element,'UNDER_REVIEW(underReview,审核中)')">审核中</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'PUBLISHED'" @click="changeCourseStatus(element,'PUBLISHED(published,已发布)')">已发布</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'DISUSE'" @click="changeCourseStatus(element,'DISUSE(disuse,停用)')">停用</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    
    </RuifoxTable>
    <!-- 分页器 -->
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn"
      :pageChoose="isPageChooseBtn"
      :options="batchOptions"
      :checkedNum="checkedNum"
      :canChoose="queryData.total > 0"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @changeAllChoose="handleAllChoose"
      @invertChoose="handleInvertChoose"
      @checkOption="handleBatchOptions"
      @refreshList="getCourseList"
      @cancelChoose="handleResetPagination"
      v-if="courseData && courseData.length > 0"
    />
    <!-- 课程信息 编辑对话框 -->
    <el-drawer
      v-model="addCourseVisible"
      :title="addCourseFlag?'新增课程':'编辑课程'"
      size="600px"
      direction="ltr"
      :before-close="closeCourse"
    >
      <el-form ref="formRef" :rules="rules" :model="addCourseForm" label-width="auto" label-position="right">
        <el-form-item label="课程名称" prop="name">
          <el-input placeholder="输入课程名称" v-model="addCourseForm.name"></el-input>
        </el-form-item>
        
        <el-form-item label="课程封面图" prop="coverImg">
          <div class="form-img" @click="handleUpload('thumb')">
            <div class="has-img" v-if="addCourseForm.coverImg && addCourseForm.coverImg != ''">
              <img :src="addCourseForm.coverImg" alt="">
              <span @click.stop="handleRemoveImg('thumb')">
                <el-icon><Delete /></el-icon>
              </span>
            </div>
            <el-icon v-else><Plus /></el-icon>
          </div>
        </el-form-item>
        <el-form-item label="课程编码" prop="code">
          <el-input placeholder="输入课程编码" v-model="addCourseForm.code"></el-input>
        </el-form-item>
        <el-form-item label="课程管理员" prop="manager">
          <el-select v-model="addCourseForm.manager" placeholder="请选择课程管理员" style="width: 240px">
            <el-option
              v-for="item in leaderList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程学分" prop="credit">
          <el-input-number v-model="addCourseForm.credit" :precision="1" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="课程类型" prop="type">
          <el-select v-model="addCourseForm.type" placeholder="选择课程类型" style="width: 240px">
            <el-option
              v-for="item in courseTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="允许的部门" prop="allowDepartments" v-if="addCourseForm.type == 'PRIVILEGED'">
          <el-cascader :options="departTree" v-model="addCourseForm.allowDepartments" clearable :props="props" :show-all-levels="false" popper-class="pid-cascader" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item label="课程说明" prop="description">
          <!-- <el-input placeholder="输入课程说明" v-model="addCourseForm.description"></el-input> -->
          <div class="description-container">
            <div class="description-item" v-for="(item,index) in addCourseForm.description" :key="index">
              <div class="item-row ">
                <span>段落名称:</span>
                <el-input v-model="item.descriptionName" placeholder="请输入段落名称" style="width: 240px"/>
                <el-icon @click="delDescription(item)" class="del-icon"><Delete /></el-icon>
              </div>
              <div class="item-row">
                <span>段落内容:</span>
                <el-input v-model="item.descriptionContent" placeholder="请输入段落内容" style="flex: 1;"  type="textarea"/>
              </div>
            </div>
            <div class="right-but">
              <el-button type="primary" link @click="addDescription">添加段落</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCourseVisible = false">取消</el-button>
          <el-button type="primary" @click="appendCourse(formRef)">确认</el-button>
        </span>
      </template>
    </el-drawer>
    <!-- 图片上传 -->
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :modelId="1" :isPublic="true" @getFileList="insertFiles" :isToJpg="true" ></FilesUpload>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import dayjs from "dayjs";
import { Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { 
  selectPageCourse,
  createCourse,
  updateByIdCourse,
  deleteByIdCourse,
  deleteByIdsCourse,
  changeStatusCourse
} from '@/api/course'
import { getDepartTree } from "@/api/depart";
import { tableList as mixTable } from "@ruifox-cms/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { FilesUpload } from "@ruifox-cms/components"
import { getUserList } from "@/api/user";
import { useStore } from "vuex";

const store = useStore();
const router = useRouter(); 

//获取负责人 走主系统根据用户角色查询
const leaderList = ref([])
const getUser = async () => {
  console.log(store);
  const res = await getUserList({
    pageSize: 15,
    currentPage: 1,
    groupId: store.state.base.userInfo.groupId
  })
  console.log("获取管理员res",res);
  if (res.code == 20000) {
    leaderList.value = res.data.list
  }
}
const defaultCourseFormData = {
  name: "",
  code: "",
  description: [],
  coverImg: "",
  credit: "",
  manager: "",
  type: "",
  allowDepartments: [],
  allowCohorts: [],
  allowUsers: []
};
const addCourseForm =  ref({ ...defaultCourseFormData });

//分页器
const {
  queryData,
  tableData: oriTableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  // isAllSearch,
  getTableData,
  //   handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectPageCourse,
  batchFuncApi: deleteByIdsCourse,
});

//分页器
const defaultQuery = reactive({
  total:10,
  currentPage: 1,
  pageSize: 10,
  id: "",
  name: "",
  description: "",
  coverImg: "",
  price: "",
  code: "",
  credit: "",
  type: "",
  status: "",
  needCheck: false,
});

Object.assign(queryData, defaultQuery);
const courseData = ref([]);

//课程类型
const courseTypeOption = ref([
  { label: "公开", value: 'PUBLIC' },
  { label: "权限", value: 'PRIVILEGED' },
]);

//课程状态
const courseStatusOption = ref([
  { label: "草稿", value: 'DRAFT' },
  { label: "已发表", value: 'PUBLISHED' },
  { label: "存档", value: 'ARCHIVED' },
]);

// 用户列表可搜索字段
const searchCmpArray = ref([
  { label: '搜索', key: 'name'},
  { label: '课程类型', key: 'type', form_type: 'select', options: courseTypeOption.value },
  { label: '课程状态', key: 'status', form_type: 'select', options: courseStatusOption.value },
  // { label: '排序', key: 'status', form_type: 'select', options: sortOption.value },
])

//跳转 课程详情
const editCourseContent = (row) => {
  router.push({ 
    name: 'examManageCourseCatalogue', 
    query: { id: row.id } 
  });
}

//编辑课程信息
const addCourseFlag = ref(false)
const addCourseVisible = ref(false)

const addCourse = () => {
  addCourseVisible.value = true
  addCourseFlag.value = true
}
const editCourseInfo = (row) => {
  addCourseVisible.value = true;
  addCourseFlag.value = false;
  addCourseForm.value = { ...row };
  console.log("addCourseForm.value",addCourseForm.value);
  // if(addCourseForm.value.description == ""){
  //   addCourseForm.value.description = [{
  //     descriptionName: "",
  //     descriptionContent: ""
  //   }]
  // }
  try {
    addCourseForm.value.description = JSON.parse(addCourseForm.value.description);
  } catch (e) {
    console.error('解析 description 失败:', e);
    // 可以选择保持原值或设置为默认值
    addCourseForm.value.description = [];
  }
  // addCourseForm.value.description = JSON.parse(addCourseForm.value.description);
  
  
}
const rules = reactive({
  code: [{ required: true, message: '请输入课程编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
  coverImg: [{ required: true, message: '请设置课程封面', trigger: 'change' }],
  // manager: [{ required: true, message: '请选择课程管理员', trigger: 'change' }],
})
const formRef = ref()

//编辑课程说明段落
const addDescription = () => {
  console.log("addCourseForm.value",addCourseForm.value);
  
  addCourseForm.value.description.push({
    descriptionName: "",
    descriptionContent: ""
  })
  console.log("addCourseForm.value",addCourseForm.value);
}
const delDescription = (item) => {
  console.log("item",item);
  
  const index = addCourseForm.value.description.indexOf(item);
  if (index > -1) {
    addCourseForm.value.description.splice(index, 1);
  }
};
//提交课程
const appendCourse = async (formEl) => {
  if (!formEl){
    ElMessage.warning("请填写完整课程信息");
    return
  } 
  await formEl.validate(async (valid) => {
    if (valid) {
      // console.log("addCourseForm.value",addCourseForm.value);
      addCourseVisible.value = false;
      if (addCourseForm.value.description) {
        addCourseForm.value.description = JSON.stringify(addCourseForm.value.description);
      }
      //判断课程状态 调用增加或者修改 课程
      if (addCourseFlag.value) {
        const res =  await createCourse(addCourseForm.value)
        if(res.code == 20000) {
          ElMessage.success('创建成功')
        } 
      } else {
        const res = await updateByIdCourse(addCourseForm.value)
        if(res.code == 20000) {
          ElMessage.success('编辑成功')
        } 
      }
      getCourseList()
    }
  })
}
const closeCourse = () => {
  ElMessageBox.confirm('是否保存该课程信息', '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await appendCourse(formRef.value)
    addCourseForm.value =  { ...defaultCourseFormData };

  }).catch(() => {
    addCourseVisible.value = false;
  })
}

//修改课程状态
const changeCourseStatus = async (row, status) => { 
  const res = await changeStatusCourse({
    id: row.id,
    status: status
  })
  if(res.code === 20000){
    ElMessage.success("修改成功");
    getCourseList()
  }
}

// 附件上传
const showFilesUpload = ref(false)
const resourceFormList = ref([])
const insertFiles = filesList => {
  resourceFormList.value = filesList.map(item => {
    return {
      resourceData: {
        title: item.name,
        url: item.url,
      },
      needUpload: item.needUpload,
      tagList: item.tagList || [],
    }
  })
  console.log("resourceFormList.value",resourceFormList.value);
  addCourseForm.value.coverImg =  resourceFormList.value[0].resourceData.url
}
const handleUpload = async () => {
  showFilesUpload.value = true
  console.log("点击上传图片");
  console.log("showFilesUpload.value",showFilesUpload.value);
  
};

const handleRemoveImg = () => {
  addCourseForm.value.coverImg =  ""
};

//获取课程数据
const getCourseList = async () => {
  const res = await selectPageCourse(queryData)
  if (res.code === 20000) {
    courseData.value = res.data.list
    oriTableData.value = res.data.list;
    queryData.total = res.data.total;
    watch(oriTableData, () => {
      
    });
  }
  
} 

// 批量操作
const batchOptions = ref([
  { name: "删除", value: "delete", icon: "&#xe74b;" }
]);
const handleBatchOptions = (data) => {
  if (data === "delete") {
    handleBatchDelete();
  } 
};

//删除课程
const removeCourse = async (row) => {
  console.log(row);
  
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选课程？</p><span style="font-size: 14px;color: #FF5240;">删除后课程将消失</span></div>',
    "删除确认",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  ).then(() => {
    deleteByIdCourse({'id': row.id}).then(() => {
      getTableData();
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
    });
  });
 
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">确认删除所选课程？删除后的课程无法恢复，请谨慎操作。</p></div>',
    "删除确认",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  ).then(() => {
    deleteByIdsCourse(checkedList.value).then(() => {
      getTableData();
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
    });
  });
};

//表格展示字段
const fieldList = ref([
  {
    title: "课程名称",
    name: "name",
  },
  {
    title: "课程封面",
    name: "coverImg",
    width: 160,
  },
  // {
  //   title: "说明",
  //   name: "description",
  // },
  {
    title: "课程编码",
    name: "code",
  },
  {
    title: "学分",
    name: "credit",
  },
  // {
  //   title: "价格",
  //   name: "price",
  // },
  {
    title: "类型",
    name: "type",
  },
  {
    title: "课程状态",
    name: "status",
  },
 
  {
    title: "操作",
    name: "options",
    width: 220,
  },
]);

//获取部门树
const departTree = ref([]);
const transformData = (data) => {
  return data.map(item => {
    const transformedItem = {
      value: item.id,
      label: item.name
    };

    if (item.children && item.children.length > 0) {
      transformedItem.children = transformData(item.children);
    }
    return transformedItem;
  });
};
const getDepartData = async () => {
  const res = await getDepartTree();
  if (res.code === 20000) {
    departTree.value = transformData(res.data.children)
  }
};

onMounted(async () => {
  await getCourseList();
  await getUser();
  await getDepartData();
})
</script>

<style scoped lang="scss">
.top-info{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  .right-box{
    display: flex;
    button{
      margin-left: 10px;
    }
  }
}
.course-thumb{
  max-width: 95%;
  height: auto;
}

.form-img{
  height: 100px;
  width: 140px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  .has-img{
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    img{
      max-width: 100%;
      max-height: 100%;
    }
    span{
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }
    &:hover{
      span{
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
.description-container{
  width: 100%;
  .description-item{
    margin-top: 10px;
    padding: 15px 15px 0;
    box-sizing: border-box;
    border: 1.5px dashed #bbb;
    border-radius: 5px;
    .item-row{
      display: flex;
      margin-bottom: 15px;
      position: relative;
      span{
        font-size: 12px;
        width: 60px;
        color: $black_2;
      }
      .del-icon{
        position: absolute;
        right: 0;
        top: 5px;
        font-size: 18px;
        color: #e85252;
        cursor: pointer;
        &:hover{
          color: #e52c2c;
        }
      }
    }
  }
}

</style>
